package com.fleapx.netty_learn.learn_beat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Author: feng peng
 * @version:: netty_heart
 * @description:
 * @create: 2021/12/3 1:57.
 */
public class BeatHandler extends SimpleChannelInboundHandler<String> {
    int readIdleTime = 0;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        System.out.println("----------------->[server] message received:"+s);
        if("I am alive".equals(s)){
            ctx.channel().writeAndFlush("you are ok?");
        }else{
            System.out.println("i am busy");
        }
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        ctx.fireUserEventTriggered(evt);
        IdleStateEvent event = (IdleStateEvent) evt;
        String eventType = null;
        switch (event.state()){
            case READER_IDLE:
                readIdleTime ++;
                eventType = "读空闲";
                break;
            case ALL_IDLE:
                eventType = "读写空闲";
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                break;
        }
        System.out.println(ctx.channel().remoteAddress()+"超时事件："+eventType);
        if(readIdleTime>3){
            System.out.println("[server] 读空闲超过3次，关闭连接");
            ctx.writeAndFlush("you are later");
            ctx.close();

        }
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        ctx.fireChannelActive();
        System.out.println("====="+ctx.channel().remoteAddress()+"i am happy client is living");
    }


}
